#include "Camera.h"

namespace egg{

    Camera::Camera(Scene* scene){
        mScene=scene;
        mFrustum.mFov=20;
        mFrustum.mFar=5;
        mFrustum.mNear=0.1;
        mViewport=new Viewport(this);
        updateTransform();
        updateProjectionMatrix();
    }

    void Camera::setFov(float value){
        mFrustum.mFov=value;
        updateProjectionMatrix();
    }

    void Camera::setFar(float value){
        if(value<mFrustum.mNear)
            LogMgr->logMessage("camera far less than near");
        mFrustum.mFar=value;
        updateProjectionMatrix();
    }

    void Camera::setNear(float value){
        if(value>mFrustum.mFar)
            LogMgr->logMessage("camera near greater than far");
        mFrustum.mNear=value;
        updateProjectionMatrix();
    }

    void Camera::updateTransform(){
        SceneNode::updateTransform();
        mViewMatrix=glm::lookAt(
            vec3(getAbsTransform()[3]),
            vec3(getAbsTransform()[3]-vec4(0,0,1,0)),
            vec3(0,1,0));
    }

    void Camera::updateProjectionMatrix(){
        mProjectionMatrix=glm::perspective(mFrustum.mFov,mViewport->getAspect(),mFrustum.mNear,mFrustum.mFar);
        mInvProjectionMatrix=glm::inverse(mProjectionMatrix);
        vec4 conner=mInvProjectionMatrix*vec4(1.0f,1.0f,1.0f,1.0f);
        conner/=conner.w;
        mFrustum.mHalfWidth=conner.x;
        mFrustum.mHalfHeight=conner.y;
    }

}